package org.yanfengying.gift.exception.handler;

import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.yanfengying.gift.exception.MyException;
import org.yanfengying.gift.exception.code.ErrorCode;
import org.yanfengying.gift.util.AjaxResult;

import java.util.List;

/**
 * 对异常进行一个统一的处理
 * 已知异常和系统异常
 */
@RestControllerAdvice
public class UnifyExceptionHandler {
    //已知异常
    @ExceptionHandler(MyException.class)
    public AjaxResult myExceptionHandler(MyException myException){
        myException.printStackTrace();//抛出异常
        return AjaxResult.me().setSuccess(false).setMessage(myException.getMessage()).setCode(myException.getCode());
    }

    //jsr303校验异常
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public AjaxResult methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e){
        e.printStackTrace();
        BindingResult bindingResult = e.getBindingResult();
        //获取错误字段
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        //格式美化
        return AjaxResult.me().setSuccess(false).setMessage(fieldErrors.toString()).setCode(ErrorCode.ERROR_CODE_400.getCode());


    }
    //未知异常
    public AjaxResult exceptionHandler(Exception e){
        e.printStackTrace();
        return AjaxResult.me().setSuccess(false).setMessage(ErrorCode.ERROR_CODE_500.getMessage()).setCode(ErrorCode.ERROR_CODE_500.getCode());
    }
}
